<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="C++,数据结构和算法,">





  <link rel="alternate" href="/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="红黑树是高效查找和插入删除的数据结构，用途很广泛，如epoll的消息注册机制，stl中的map都采用了红黑树。 红黑树的主要特性：（1）每个节点或者是黑色，或者是红色。（2）根节点是黑色。（3）每个叶子节点（NIL）是黑色。 [注意：这里叶子节点，是指为空的叶子节点！]（4）如果一个节点是红色的，则它的子节点必须是黑色的。（5）从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。 定理：">
<meta name="keywords" content="C++,数据结构和算法">
<meta property="og:type" content="article">
<meta property="og:title" content="红黑树的原理和实现">
<meta property="og:url" content="http://www.limerence2017.com/2017/10/18/rbtree/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="红黑树是高效查找和插入删除的数据结构，用途很广泛，如epoll的消息注册机制，stl中的map都采用了红黑树。 红黑树的主要特性：（1）每个节点或者是黑色，或者是红色。（2）根节点是黑色。（3）每个叶子节点（NIL）是黑色。 [注意：这里叶子节点，是指为空的叶子节点！]（4）如果一个节点是红色的，则它的子节点必须是黑色的。（5）从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。 定理：">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/1.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/2.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/3.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/4.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/1.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/2.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/3.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/4.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/5.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/6.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/7.jpg">
<meta property="og:image" content="http://www.limerence2017.com/2017/10/18/rbtree/8.jpg">
<meta property="og:updated_time" content="2020-06-22T09:30:59.090Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="红黑树的原理和实现">
<meta name="twitter:description" content="红黑树是高效查找和插入删除的数据结构，用途很广泛，如epoll的消息注册机制，stl中的map都采用了红黑树。 红黑树的主要特性：（1）每个节点或者是黑色，或者是红色。（2）根节点是黑色。（3）每个叶子节点（NIL）是黑色。 [注意：这里叶子节点，是指为空的叶子节点！]（4）如果一个节点是红色的，则它的子节点必须是黑色的。（5）从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。 定理：">
<meta name="twitter:image" content="http://www.limerence2017.com/2017/10/18/rbtree/1.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.limerence2017.com/2017/10/18/rbtree/">





  <title>红黑树的原理和实现 | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.limerence2017.com/2017/10/18/rbtree/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">红黑树的原理和实现</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-10-18T15:01:35+08:00">
                2017-10-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/stl/" itemprop="url" rel="index">
                    <span itemprop="name">数据结构和算法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>红黑树是高效查找和插入删除的数据结构，用途很广泛，如epoll的消息注册机制，stl中的map都采用了红黑树。</p>
<h2 id="红黑树的主要特性："><a href="#红黑树的主要特性：" class="headerlink" title="红黑树的主要特性："></a>红黑树的主要特性：</h2><p><code>（1）每个节点或者是黑色，或者是红色。</code><br><code>（2）根节点是黑色。</code><br><code>（3）每个叶子节点（NIL）是黑色。 [注意：这里叶子节点，是指为空的叶子节点！]</code><br><code>（4）如果一个节点是红色的，则它的子节点必须是黑色的。</code><br><code>（5）从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。</code></p>
<p>定理：<code>一棵含有n个节点的红黑树的高度至多为2log(n+1)。</code><br><a id="more"></a><br>定义节点为TreeNode，TreeNode类内容如下：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	TreeNode():m_pParent(<span class="literal">NULL</span>), m_pLeftChild(<span class="literal">NULL</span>), m_pRightChild(<span class="literal">NULL</span>), m_nData(<span class="number">0</span>), m_nColor(RED)&#123;&#125;</span><br><span class="line">	TreeNode(<span class="keyword">const</span> TreeNode &amp; tree)&#123;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_nData = tree.m_nData;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_pParent = <span class="literal">NULL</span>;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_pLeftChild = <span class="literal">NULL</span>;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_pRightChild = <span class="literal">NULL</span>;</span><br><span class="line">		m_nColor = tree.m_nColor;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	TreeNode(<span class="keyword">int</span> data):m_nData(data), m_pRightChild(<span class="literal">NULL</span>), m_pLeftChild(<span class="literal">NULL</span>), m_pParent(<span class="literal">NULL</span>),m_nColor(RED)&#123;&#125;</span><br><span class="line">	~TreeNode()&#123; </span><br><span class="line">		<span class="keyword">this</span>-&gt;m_nData = <span class="number">0</span>;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_pLeftChild = <span class="literal">NULL</span>;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_pParent = <span class="literal">NULL</span>;</span><br><span class="line">		<span class="keyword">this</span>-&gt;m_pRightChild = <span class="literal">NULL</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	TreeNode&amp; <span class="keyword">operator</span> =(<span class="keyword">const</span> TreeNode&amp; treeNode)<span class="comment">//赋值运算符</span></span><br><span class="line">	&#123;</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span> != &amp;treeNode)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">this</span>-&gt;m_pParent = treeNode.m_pParent;</span><br><span class="line">			<span class="keyword">this</span>-&gt;m_pLeftChild = treeNode.m_pLeftChild;</span><br><span class="line">			<span class="keyword">this</span>-&gt;m_pRightChild = treeNode.m_pRightChild;</span><br><span class="line">			<span class="keyword">this</span>-&gt;m_nData = treeNode.m_nData;</span><br><span class="line">			<span class="keyword">this</span>-&gt;m_nColor = treeNode.m_nColor;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> *<span class="keyword">this</span>;</span><br><span class="line">	&#125; </span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">		</span><br><span class="line">	<span class="keyword">friend</span> ostream &amp; <span class="keyword">operator</span>&lt;&lt;(ostream &amp;out, TreeNode &amp;obj)</span><br><span class="line">	&#123;</span><br><span class="line">		out &lt;&lt;  <span class="string">" "</span> &lt;&lt; obj.m_nData &lt;&lt;<span class="string">" "</span>;</span><br><span class="line">		<span class="keyword">return</span> out;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	TreeNode * m_pParent;</span><br><span class="line">	TreeNode * m_pLeftChild;</span><br><span class="line">	TreeNode * m_pRightChild;</span><br><span class="line">	<span class="keyword">int</span> m_nData;	</span><br><span class="line">	<span class="keyword">int</span> m_nColor;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h2 id="树的左旋和右旋"><a href="#树的左旋和右旋" class="headerlink" title="树的左旋和右旋"></a>树的左旋和右旋</h2><p>左旋：<br><img src="1.jpg" alt="1.jpg"><br>用C++实现左旋<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//节点X左旋</span></span><br><span class="line"><span class="keyword">void</span> TreeClass::leftRotate(TreeNode * x)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">if</span>(x-&gt;m_pRightChild == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//取X的右孩子为y</span></span><br><span class="line">	TreeNode * y = x-&gt;m_pRightChild; </span><br><span class="line">	<span class="comment">//判断y是否有左孩子</span></span><br><span class="line">	<span class="keyword">if</span>(y-&gt;m_pLeftChild)</span><br><span class="line">	&#123;</span><br><span class="line">		x-&gt;m_pRightChild = y-&gt;m_pLeftChild;</span><br><span class="line">		y-&gt;m_pLeftChild-&gt;m_pParent = x;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//x的父节点赋值为y的父节点</span></span><br><span class="line">	y-&gt;m_pParent = x-&gt;m_pParent;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(x-&gt;m_pParent == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//X为root节点，将y设置为root节点</span></span><br><span class="line">		m_pRoot = y; </span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(x == x-&gt;m_pParent-&gt;m_pLeftChild)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//X为其父节点的左孩子，将y设置为其父节点的左孩子</span></span><br><span class="line">		x-&gt;m_pParent-&gt;m_pLeftChild = y;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//X为其父节点的右孩子，将y设置为其父节点的右孩子</span></span><br><span class="line">		x-&gt;m_pParent-&gt;m_pRightChild = y;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//将X设置为y的左孩子</span></span><br><span class="line">	y-&gt;m_pLeftChild = x;</span><br><span class="line">	x-&gt;m_pParent = y;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>如下图为左旋40节点<br><img src="2.jpg" alt="2.jpg"><br>右旋：<br><img src="3.jpg" alt="3.jpg"><br>用C++实现y节点右旋<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**************</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">		y                        x</span></span><br><span class="line"><span class="comment">	   / \                      / \</span></span><br><span class="line"><span class="comment">      x    m  ===&gt;      z   y</span></span><br><span class="line"><span class="comment">	 / \                           / \</span></span><br><span class="line"><span class="comment">	z   h                        h   m</span></span><br><span class="line"><span class="comment">****************/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> TreeClass::rightRotate(TreeNode * y)</span><br><span class="line">&#123;</span><br><span class="line">	TreeNode * x = y-&gt;m_pLeftChild;</span><br><span class="line">	<span class="keyword">if</span>(x == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(x-&gt;m_pRightChild)</span><br><span class="line">	&#123;</span><br><span class="line">		 <span class="comment">// 将 “y” 设为 “x的右孩子的父亲”</span></span><br><span class="line">		x-&gt;m_pRightChild-&gt;m_pParent = y;</span><br><span class="line">		<span class="comment">// 将 “x的右孩子” 设为 “y的左孩子”</span></span><br><span class="line">		y-&gt;m_pLeftChild = x-&gt;m_pRightChild;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		y-&gt;m_pLeftChild = <span class="literal">NULL</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	x-&gt;m_pParent = y-&gt;m_pParent ;</span><br><span class="line">	<span class="keyword">if</span>(y-&gt;m_pParent == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		 <span class="comment">// 情况1：如果 “y的父亲” 是空节点，则将x设为根节点</span></span><br><span class="line">		m_pRoot = x;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(y == y-&gt;m_pParent-&gt;m_pRightChild)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//如果 y是它父节点的右孩子，则将x设为“y的父节点的左孩子”</span></span><br><span class="line">		y-&gt;m_pParent-&gt;m_pRightChild = x;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//(y是它父节点的左孩子) 将x设为“y的父节点的左孩子”</span></span><br><span class="line">		y-&gt;m_pParent-&gt;m_pLeftChild = x;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//y设置为x的右孩子</span></span><br><span class="line">	x-&gt;m_pRightChild = y;</span><br><span class="line">	y-&gt;m_pParent = x;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>右旋示意图<br><img src="4.jpg" alt="4.jpg"></p>
<h2 id="红黑树的插入"><a href="#红黑树的插入" class="headerlink" title="红黑树的插入"></a>红黑树的插入</h2><p>红黑树的插入分三步：<br><code>1.将红黑树当作一颗二叉查找树，将节点插入</code><br><code>2.将插入的节点着色为&quot;红色&quot;</code><br><code>3.通过一系列的旋转或着色等操作，使之重新成为一颗红黑树</code><br>将节点插入后着色为红色可能会导致红黑树特性失效，有可能使特性(4)失效：如果一个节点是红色的，则它的子节点必须是黑色的。<br>前面将结果二叉搜索树的插入，这里和之前类似，不再赘述，C++实现如下：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> TreeClass::rbInsertNode(TreeNode * z)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="comment">//定义一个节点的指针</span></span><br><span class="line">	TreeNode * y = <span class="literal">NULL</span>;</span><br><span class="line">	TreeNode * x = m_pRoot;</span><br><span class="line">	<span class="comment">//循环查找节点z插入的位置，指导找到叶子结点</span></span><br><span class="line">	<span class="keyword">while</span>(x)</span><br><span class="line">	&#123;</span><br><span class="line">		y = x;</span><br><span class="line">		<span class="keyword">if</span>(z-&gt;m_nData &lt; x-&gt;m_nData)</span><br><span class="line">		&#123;</span><br><span class="line">			x = x-&gt;m_pLeftChild;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			x = x-&gt;m_pRightChild;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//循环结束时，x指向某个叶子结点，y指向x的父亲</span></span><br><span class="line">	<span class="comment">//设置z的父节点为y</span></span><br><span class="line">	z-&gt;m_pParent = y;</span><br><span class="line">	<span class="comment">//如果y为NULL，设置z为root节点</span></span><br><span class="line">	<span class="keyword">if</span>(y == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		m_pRoot = z;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(z-&gt;m_nData &lt; y-&gt;m_nData)</span><br><span class="line">	&#123;</span><br><span class="line">		y-&gt;m_pLeftChild = z;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		y-&gt;m_pRightChild = z;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// z的左孩子设为空</span></span><br><span class="line">	z-&gt;m_pLeftChild = <span class="literal">NULL</span>;</span><br><span class="line">	 <span class="comment">// z的右孩子设为空</span></span><br><span class="line">	z-&gt;m_pRightChild = <span class="literal">NULL</span>;</span><br><span class="line">	<span class="comment">// 将z着色为“红色”</span></span><br><span class="line">	z-&gt;m_nColor = RED;</span><br><span class="line">	<span class="comment">//通过rbInsertFixUp(z)对红黑树的节点进行颜色修改以及旋转，让树T仍然是一颗红黑树</span></span><br><span class="line">	rbInsertFixUp(z);				</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>根据被插入节点的父节点的情况，可以将”当节点z被着色为红色节点，并插入二叉树”划分为三种情况来处理。<br>① 情况说明：被插入的节点是根节点。<br>   处理方法：直接把此节点涂为黑色。<br>② 情况说明：被插入的节点的父节点是黑色。<br>   处理方法：什么也不需要做。节点被插入后，仍然是红黑树。<br>③ 情况说明：被插入的节点的父节点是红色。<br>   处理方法：那么，该情况与红黑树的“特性(4)”相冲突。这种情况下，被插入节点是一定存在非空祖父节点的；进一步的讲，被插入节点也一定存在叔叔节点(即使叔叔节点为空，我们也视之为存在，空节点本身就是黑色节点)。理解这点之后，我们依据”叔叔节点的情况”，将这种情况进一步划分为3种情况(Case)。</p>
<h3 id="case1-当前节点的父节点是红色，且当前节点的祖父节点的另一个子节点（叔叔节点）也是红色。"><a href="#case1-当前节点的父节点是红色，且当前节点的祖父节点的另一个子节点（叔叔节点）也是红色。" class="headerlink" title="case1 当前节点的父节点是红色，且当前节点的祖父节点的另一个子节点（叔叔节点）也是红色。"></a>case1 当前节点的父节点是红色，且当前节点的祖父节点的另一个子节点（叔叔节点）也是红色。</h3><p>处理策略<br>(01) 将“父节点”设为黑色。<br>(02) 将“叔叔节点”设为黑色。<br>(03) 将“祖父节点”设为“红色”。<br>(04) 将“祖父节点”设为“当前节点”(红色节点)；即，之后继续对“当前节点”进行操作。</p>
<p>这么做的目的是保持黑色节点数量一致，并且将红色节点上移，直到其为根，将根节点设置为红色。<br>如下图为case1：<br><img src="1.png" alt="1.png"></p>
<h3 id="case2-当前节点的父节点是红色，当前节点的叔叔节点为黑色。分为四种情况。在case2中只讨论前两种，后面两种归类为case3"><a href="#case2-当前节点的父节点是红色，当前节点的叔叔节点为黑色。分为四种情况。在case2中只讨论前两种，后面两种归类为case3" class="headerlink" title="case2 当前节点的父节点是红色，当前节点的叔叔节点为黑色。分为四种情况。在case2中只讨论前两种，后面两种归类为case3"></a>case2 当前节点的父节点是红色，当前节点的叔叔节点为黑色。分为四种情况。在case2中只讨论前两种，后面两种归类为case3</h3><p><code>case 2.1  当前节点父节点是其祖父节点的左孩子，当前节点是其父节点的右孩子，那么以当前节点的父节点为
支点进行左旋</code>，如下图：<br><img src="2.png" alt="2.png"><br><code>case 2.1  当前节点父节点是其祖父节点的右孩子，当前节点是其父节点的左孩子，那么以当前节点的父节点为
支点进行右旋</code>，如下图：<br><img src="3.png" alt="3.png"><br>综上所述：case2的两种情况就是将父节点和子节点通过旋转放置在一侧。</p>
<h3 id="case3-当前节点的父节点是红色，当前节点的叔叔节点是黑色，和case2两种情况不同的是"><a href="#case3-当前节点的父节点是红色，当前节点的叔叔节点是黑色，和case2两种情况不同的是" class="headerlink" title="case3 当前节点的父节点是红色，当前节点的叔叔节点是黑色，和case2两种情况不同的是"></a>case3 当前节点的父节点是红色，当前节点的叔叔节点是黑色，和case2两种情况不同的是</h3><p><code>case3.1 当前节点父节点是其祖父节点的左孩子，当前节点是其父节点的左孩子，那么将父节点设置为黑色，祖父节点设置为红色，
以祖父节点为支点右旋</code>，如下图：<br><img src="4.png" alt="4.png"><br><code>case3.2 当前节点父节点是其祖父节点的右孩子，且当前节点是其父节点的右孩子，那么将父节点设置为黑色，祖父节点设置为红色，
以祖父节点为支点进行左旋</code>，同上例子，不再赘述，只是左右不同。<br>将上述着色和旋转过程完善，封装为rbInsertFixUp()函数如下<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//重新着色和旋转</span></span><br><span class="line"><span class="keyword">void</span> TreeClass::rbInsertFixUp(TreeNode * z)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="comment">//z为root节点，那么只需要设置z颜色为黑色即可。</span></span><br><span class="line">	<span class="keyword">if</span>(z-&gt;m_pParent == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		m_pRoot-&gt;m_nColor = BLACK;</span><br><span class="line">		<span class="keyword">return</span> ;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//若当前节点z的父节点为红色，需要一直调色和旋转，直到z为黑色为止</span></span><br><span class="line">	<span class="keyword">while</span>(z-&gt;m_pParent-&gt;m_nColor == RED)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">// 若“z的父节点”是“z的祖父节点的左孩子”，则进行以下处理。</span></span><br><span class="line">		<span class="keyword">if</span>(z-&gt;m_pParent-&gt;m_pParent-&gt;m_pLeftChild == z-&gt;m_pParent)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">// 将y设置为“z的叔叔节点(z的祖父节点的右孩子)”</span></span><br><span class="line">			TreeNode * y = z-&gt;m_pParent-&gt;m_pParent-&gt;m_pRightChild;</span><br><span class="line">			 <span class="comment">// Case 1条件：叔叔是红色</span></span><br><span class="line">			<span class="keyword">if</span>(y-&gt;m_nColor == RED)</span><br><span class="line">			&#123;</span><br><span class="line">				 <span class="comment">//  (01) 将“父节点”设为黑色</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_nColor = BLACK;</span><br><span class="line">				 <span class="comment">//  (02) 将“叔叔节点”设为黑色</span></span><br><span class="line">				y-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">// (03)将“祖父节点”设为“红色”</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_pParent-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//  (04) 将“祖父节点”设为“当前节点”(红色节点)</span></span><br><span class="line">				z = z-&gt;m_pParent-&gt;m_pParent;</span><br><span class="line">			&#125;<span class="comment">//if(y-&gt;m_nColor == RED)</span></span><br><span class="line">			<span class="keyword">else</span> </span><br><span class="line">			&#123;</span><br><span class="line">				 <span class="comment">// Case 2条件：叔叔是黑色，且当前节点是右孩子</span></span><br><span class="line">				<span class="keyword">if</span>(z == z-&gt;m_pParent-&gt;m_pRightChild)</span><br><span class="line">				&#123;</span><br><span class="line">					<span class="comment">//  (01) 将“父节点”作为“新的当前节点”</span></span><br><span class="line">					z = z-&gt;m_pParent;</span><br><span class="line">					<span class="comment">//  (02) 以“新的当前节点”为支点进行左旋</span></span><br><span class="line">					leftRotate(z);</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="comment">// Case 3条件：叔叔是黑色，且当前节点是左孩子。(01) 将“父节点”设为“黑色”。</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//  (02) 将“祖父节点”设为“红色”。</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_pParent-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//  (03) 以“祖父节点”为支点进行右旋。</span></span><br><span class="line">				rightRotate(z-&gt;m_pParent-&gt;m_pParent);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;<span class="comment">//if(z-&gt;m_pParent-&gt;m_pParent-&gt;m_pLeftChild == z-&gt;m_pParent)</span></span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">// 若“z的父节点”是“z的祖父节点的右孩子”，将上面的操作中“right”和“left”交换位置，然后依次执行。</span></span><br><span class="line">			TreeNode * y = z-&gt;m_pParent-&gt;m_pParent-&gt;m_pLeftChild;</span><br><span class="line">			<span class="comment">// Case 1条件：叔叔是红色</span></span><br><span class="line">			<span class="keyword">if</span>(y-&gt;m_nColor == RED)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="comment">//  (01) 将“父节点”设为黑色</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//  (02) 将“叔叔节点”设为黑色</span></span><br><span class="line">				y-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">// (03)将“祖父节点”设为“红色”</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_pParent-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//  (04) 将“祖父节点”设为“当前节点”(红色节点)</span></span><br><span class="line">				z = z-&gt;m_pParent-&gt;m_pParent;</span><br><span class="line">			&#125;<span class="comment">//if(y-&gt;m_nColor == RED)</span></span><br><span class="line">			<span class="keyword">else</span> </span><br><span class="line">			&#123;</span><br><span class="line">				<span class="comment">// Case 2条件：叔叔是黑色，且当前节点是左孩子</span></span><br><span class="line">				<span class="keyword">if</span>(z == z-&gt;m_pParent-&gt;m_pLeftChild)</span><br><span class="line">				&#123;</span><br><span class="line">					<span class="comment">//  (01) 将“父节点”作为“新的当前节点”</span></span><br><span class="line">					z = z-&gt;m_pParent;</span><br><span class="line">					<span class="comment">//  (02) 以“新的当前节点”为支点进行右旋</span></span><br><span class="line">					rightRotate(z);</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="comment">// Case 3条件：叔叔是黑色，且当前节点是右孩子。(01) 将“父节点”设为“黑色”。</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//  (02) 将“祖父节点”设为“红色”。</span></span><br><span class="line">				z-&gt;m_pParent-&gt;m_pParent-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//  (03) 以“祖父节点”为支点进行右旋。</span></span><br><span class="line">				leftRotate(z-&gt;m_pParent-&gt;m_pParent);</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line">	</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//最后将root节点设置为黑色</span></span><br><span class="line">	m_pRoot-&gt;m_nColor = BLACK;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>读者可以反复推敲上面代码，下面介绍红黑树的删除。红黑树的删除和普通的二叉搜索树一样，只是删除后多增加一些旋转和调节颜色的手段。<br>先删除节点z，然后在旋转和着色。如果节点z仅有一个孩子或者没有孩子，直接删除，并用子节点替代它即可。如果z有两个孩子，那么找到后继<br>节点，将z替换为后继节点的数值，并且删除后继节点，再对后继节点的孩子进行旋转和着色即可。<br>下面是红黑树删除的代码<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">TreeNode *  TreeClass::rbDeleteNode(TreeNode * z)</span><br><span class="line">&#123;</span><br><span class="line">	TreeNode * y = <span class="literal">NULL</span>;</span><br><span class="line">	TreeNode * x = <span class="literal">NULL</span>;</span><br><span class="line">	<span class="comment">//z只有一个孩子或者没有孩子，那么删除z，将孩子连接到父节点即可</span></span><br><span class="line">	<span class="keyword">if</span>(z-&gt;m_pLeftChild == <span class="literal">NULL</span> || z-&gt;m_pRightChild == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		 y = z;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="comment">//z有两个孩子，那么将z的后继节点替换z的数值，删除后继节点即可。</span></span><br><span class="line">		y = findNextNode(z);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//找到节点y的子树，节点y的子树为空或者只有一支，不存在双子树情况。</span></span><br><span class="line">	<span class="comment">//因为如果z只有一个孩子或者没有孩子，那么y==z，如果z有两个孩子，那么y==z的后继节点，</span></span><br><span class="line">	<span class="comment">//z的后继节点一定只有一个孩子或者没有孩子。</span></span><br><span class="line">	<span class="keyword">if</span>(y-&gt;m_pLeftChild)</span><br><span class="line">	&#123;</span><br><span class="line">		x = y-&gt;m_pLeftChild;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		x = y-&gt;m_pRightChild;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(x)</span><br><span class="line">	&#123;</span><br><span class="line">		x-&gt;m_pParent = y-&gt;m_pParent;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(y-&gt;m_pParent == <span class="literal">NULL</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		m_pRoot = x;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(y == y-&gt;m_pParent-&gt;m_pLeftChild)</span><br><span class="line">	&#123;</span><br><span class="line">		y-&gt;m_pParent-&gt;m_pLeftChild = x;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span></span><br><span class="line">	&#123;</span><br><span class="line">		y-&gt;m_pParent-&gt;m_pRightChild = x;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	 <span class="keyword">if</span>(y != z)</span><br><span class="line">	 &#123;</span><br><span class="line">		 <span class="comment">// 若“y的值” 赋值给 “z”。注意：这里只拷贝z的值给y，而没有拷贝z的颜色</span></span><br><span class="line">		 z-&gt;m_nData = y-&gt;m_nData;</span><br><span class="line">	 &#125;</span><br><span class="line">	</span><br><span class="line">	 <span class="keyword">if</span>(y-&gt;m_nColor == BLACK)</span><br><span class="line">	 &#123;</span><br><span class="line">		rbDeleteFixUp(x);</span><br><span class="line">	 &#125;</span><br><span class="line">	 <span class="keyword">return</span> y;</span><br><span class="line">	 </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对于删除的旋转和颜色变换是有规律的，由于红黑树是由2-3树变化而来，所以想了解红黑树删除原理需要进一步了解2-3树即可。<br>我只是根据算法导论和红黑树原理进行总结。对于节点X旋转和着色可以概括为3种情况。<br>① 情况说明：x是红色节点。<br>    处理方法：直接把x设为黑色，结束。此时红黑树性质全部恢复。<br>② 情况说明：x是黑节点，且x是根。<br>    处理方法：什么都不做，结束。此时红黑树性质全部恢复。<br>③ 情况说明：x是黑节点，且x不是根。红黑树的删除分如下四种情况：<br><code>Case 1    x是黑节点，x的兄弟节点是红色</code><br><code>Case 1.1 如果x是其父节点的左孩子， 将x的兄弟节点设为黑色，将x的父节点设为红色，对x的父节点进行左旋， 
左旋后重新设置x的兄弟节点</code><br><code>Case 1.2 如果x是其父节点的右孩子， 将x的兄弟节点设为黑色，将x的父节点设为红色，对x的父节点进行右旋， 
左旋后重新设置x的兄弟节点</code><br>如下图所示<br><img src="5.jpg" alt="5.jpg"></p>
<p><code>Case 2    x是黑节点，x的兄弟节点是黑色，x的兄弟节点的两个孩子都是黑色,将x的兄弟节点设为红色, 设置x的父节点为新的x节点</code>。<br>处理结果如下图：<br><img src="6.jpg" alt="6.jpg"><br><code>Case 3    x是黑节点，x的兄弟节点是黑色；</code><br><code>Case 3.1 x是其父节点的左孩子，X的兄弟节点的左孩子是红色，右孩子是黑色的,</code>解决策略如下：<br>(01) 将x兄弟节点的左孩子设为“黑色”。<br>(02) 将x兄弟节点设为“红色”。<br>(03) 对x的兄弟节点进行右旋。<br>(04) 右旋后，重新设置x的兄弟节点。<br><code>Case 3.2 x是其父节点的右孩子，x的兄弟节点的右孩子是红色，左孩子是黑色的,</code>解决策略如下：<br>(01) 将x兄弟节点的右孩子设为“黑色”。<br>(02) 将x兄弟节点设为“红色”。<br>(03) 对x的兄弟节点进行左旋。<br>(04) 左旋后，重新设置x的兄弟节点。<br><img src="7.jpg" alt="7.jpg"></p>
<p><code>Case 4    x是黑节点，x的兄弟节点是黑色；</code>Case 4.1 x是其父节点的左孩子，x的兄弟节点的右孩子是红色的，x的兄弟节点的左孩子任意颜色<code>(01) 将x父节点颜色 赋值给 x的兄弟节点。
(02) 将x父节点设为“黑色”。
(03) 将x兄弟节点的右子节设为“黑色”。
(04) 对x的父节点进行左旋。
(05) 设置“x”为“根节点”。</code>Case 4.2 x是其父节点的右孩子，x的兄弟节点的左孩子是红色的，x的兄弟节点的右孩子任意颜色`<br>(01) 将x父节点颜色 赋值给 x的兄弟节点。<br>(02) 将x父节点设为“黑色”。<br>(03) 将x兄弟节点的左孩子设为“黑色”。<br>(04) 对x的父节点进行右旋。<br>(05) 设置“x”为“根节点”。<br><img src="8.jpg" alt="8.jpg"><br>用C++实现上述旋转和着色过程。<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> TreeClass::rbDeleteFixUp(TreeNode * x)</span><br><span class="line">&#123;</span><br><span class="line">	<span class="keyword">while</span>(x != m_pRoot &amp;&amp; x-&gt;m_nColor == BLACK)</span><br><span class="line">	&#123;</span><br><span class="line">		<span class="keyword">if</span>(x-&gt;m_pParent-&gt;m_pLeftChild == x)</span><br><span class="line">		&#123;</span><br><span class="line">			TreeNode * w = x-&gt;m_pParent-&gt;m_pRightChild;</span><br><span class="line">			<span class="comment">// Case 1: x是黑节点，x的兄弟节点是红色。</span></span><br><span class="line">			<span class="keyword">if</span>(w-&gt;m_nColor == RED)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="comment">//   (01) 将x的兄弟节点设为“黑色”。</span></span><br><span class="line">				w-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//   (02) 将x的父节点设为“红色”。</span></span><br><span class="line">				x-&gt;m_pParent-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//   (03) 对x的父节点进行左旋。</span></span><br><span class="line">				leftRotate(x-&gt;m_pParent);</span><br><span class="line">				<span class="comment">//   (04) 左旋后，重新设置x的兄弟节点。</span></span><br><span class="line">				w = x-&gt;m_pParent-&gt;m_pRightChild;</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">			<span class="comment">// Case 2: x是黑节点，x的兄弟节点是黑色，x的兄弟节点的两个孩子都是黑色。</span></span><br><span class="line">			<span class="keyword">if</span>(w-&gt;m_pLeftChild-&gt;m_nColor == BLACK &amp;&amp; w-&gt;m_pRightChild-&gt;m_nColor == BLACK)</span><br><span class="line">			&#123;</span><br><span class="line">				 <span class="comment">//   (01) 将x的兄弟节点设为“红色”</span></span><br><span class="line">				w-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//   (02) 设置“x的父节点”为“新的x节点”。</span></span><br><span class="line">				x = x-&gt;m_pParent;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> </span><br><span class="line">			&#123;</span><br><span class="line">				 <span class="comment">// Case 3: x是黑节点，x的兄弟节点是黑色；x的兄弟节点的左孩子是红色，右孩子是黑色的</span></span><br><span class="line">				<span class="keyword">if</span>(w-&gt;m_pRightChild-&gt;m_nColor == BLACK)</span><br><span class="line">				&#123;</span><br><span class="line">					<span class="comment">//   (01) 将x兄弟节点的左孩子设为“黑色”</span></span><br><span class="line">					w-&gt;m_pLeftChild-&gt;m_nColor = BLACK;</span><br><span class="line">					<span class="comment">//   (02) 将x兄弟节点设为“红色”</span></span><br><span class="line">					w-&gt;m_nColor = RED;</span><br><span class="line">					<span class="comment">//   (03) 对x的兄弟节点进行右旋</span></span><br><span class="line">					rightRotate(w);</span><br><span class="line">					 <span class="comment">//   (04) 右旋后，重新设置x的兄弟节点。</span></span><br><span class="line">					w = x-&gt;m_pParent-&gt;m_pRightChild;</span><br><span class="line">				&#125;</span><br><span class="line"></span><br><span class="line">				<span class="comment">// Case 4: x是黑节点，x的兄弟节点是黑色；x的兄弟节点的右孩子是红色的。</span></span><br><span class="line">				<span class="comment">//(01) 将x父节点颜色 赋值给 x的兄弟节点。</span></span><br><span class="line">				w-&gt;m_nColor = x-&gt;m_pParent-&gt;m_nColor;</span><br><span class="line">				 <span class="comment">//   (02) 将x父节点设为“黑色”</span></span><br><span class="line">				x-&gt;m_pParent-&gt;m_nColor = BLACK;</span><br><span class="line">				 <span class="comment">//   (03) 将x兄弟节点的右子节设为“黑色”。</span></span><br><span class="line">				x-&gt;m_pRightChild-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//  (04) 对x的父节点进行左旋。</span></span><br><span class="line">				leftRotate(x-&gt;m_pParent);</span><br><span class="line">				x = m_pRoot;</span><br><span class="line">					</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">		&#125;<span class="comment">//if(x-&gt;m_pParent-&gt;m_pLeftChild == x)</span></span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">// 若 “x”是“它父节点的右孩子”，将上面的操作中“right”和“left”交换位置，然后依次执行</span></span><br><span class="line">			TreeNode * w = x-&gt;m_pParent-&gt;m_pLeftChild;</span><br><span class="line">			<span class="comment">// Case 1: x是黑节点，x的兄弟节点是红色。</span></span><br><span class="line">			<span class="keyword">if</span>(w-&gt;m_nColor == RED)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="comment">//   (01) 将x的兄弟节点设为“黑色”。</span></span><br><span class="line">				w-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//   (02) 将x的父节点设为“红色”。</span></span><br><span class="line">				x-&gt;m_pParent-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//   (03) 对x的父节点进行右旋。</span></span><br><span class="line">				rightRotate(x-&gt;m_pParent);</span><br><span class="line">				<span class="comment">//   (04) 右旋后，重新设置x的兄弟节点。</span></span><br><span class="line">				w = x-&gt;m_pParent-&gt;m_pLeftChild;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="comment">// Case 2: x是黑节点，x的兄弟节点是黑色，x的兄弟节点的两个孩子都是黑色。</span></span><br><span class="line">			<span class="keyword">if</span>(w-&gt;m_pLeftChild-&gt;m_nColor == BLACK &amp;&amp; w-&gt;m_pRightChild-&gt;m_nColor == BLACK)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="comment">//   (01) 将x的兄弟节点设为“红色”</span></span><br><span class="line">				w-&gt;m_nColor = RED;</span><br><span class="line">				<span class="comment">//   (02) 设置“x的父节点”为“新的x节点”。</span></span><br><span class="line">				x = x-&gt;m_pParent;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> </span><br><span class="line">			&#123;</span><br><span class="line">				<span class="comment">// Case 3: x是黑节点，x的兄弟节点是黑色；x的兄弟节点的左孩子是黑色，右孩子是红色的</span></span><br><span class="line">				<span class="keyword">if</span>(w-&gt;m_pLeftChild-&gt;m_nColor == BLACK)</span><br><span class="line">				&#123;</span><br><span class="line">					<span class="comment">//   (01) 将x兄弟节点的右孩子设为“黑色”</span></span><br><span class="line">					w-&gt;m_pRightChild-&gt;m_nColor = BLACK;</span><br><span class="line">					<span class="comment">//   (02) 将x兄弟节点设为“红色”</span></span><br><span class="line">					w-&gt;m_nColor = RED;</span><br><span class="line">					<span class="comment">//   (03) 对x的兄弟节点进行左旋</span></span><br><span class="line">					leftRotate(w);</span><br><span class="line">					<span class="comment">//   (04) 左旋后，重新设置x的兄弟节点。</span></span><br><span class="line">					w = x-&gt;m_pParent-&gt;m_pLeftChild;</span><br><span class="line">				&#125;</span><br><span class="line"></span><br><span class="line">				<span class="comment">// Case 4: x是黑节点，x的兄弟节点是黑色；x的兄弟节点的左孩子是红色的。</span></span><br><span class="line">				<span class="comment">//(01) 将x父节点颜色 赋值给 x的兄弟节点。</span></span><br><span class="line">				w-&gt;m_nColor = x-&gt;m_pParent-&gt;m_nColor;</span><br><span class="line">				<span class="comment">//   (02) 将x父节点设为“黑色”</span></span><br><span class="line">				x-&gt;m_pParent-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//   (03) 将x兄弟节点的左子节设为“黑色”。</span></span><br><span class="line">				x-&gt;m_pLeftChild-&gt;m_nColor = BLACK;</span><br><span class="line">				<span class="comment">//  (04) 对x的父节点进行右旋。</span></span><br><span class="line">				rightRotate(x-&gt;m_pParent);</span><br><span class="line">				x = m_pRoot;</span><br><span class="line"></span><br><span class="line">			&#125;</span><br><span class="line">		&#125; <span class="comment">//else</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	x-&gt;m_nColor = BLACK;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到此为止红黑树的实现和原理介绍完毕，读者熟悉后可以利用红黑树做一些排序和高效的数据处理。<br>源码下载：<br><a href="https://github.com/secondtonone1/RBTree" target="_blank" rel="noopener">https://github.com/secondtonone1/RBTree</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C/" rel="tag"># C++</a>
          
            <a href="/tags/数据结构和算法/" rel="tag"># 数据结构和算法</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/09/searchtree/" rel="next" title="二叉搜索树">
                <i class="fa fa-chevron-left"></i> 二叉搜索树
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/14/pythonio/" rel="prev" title="python文件读写和序列化">
                python文件读写和序列化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#红黑树的主要特性："><span class="nav-number">1.</span> <span class="nav-text">红黑树的主要特性：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#树的左旋和右旋"><span class="nav-number">2.</span> <span class="nav-text">树的左旋和右旋</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#红黑树的插入"><span class="nav-number">3.</span> <span class="nav-text">红黑树的插入</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#case1-当前节点的父节点是红色，且当前节点的祖父节点的另一个子节点（叔叔节点）也是红色。"><span class="nav-number">3.1.</span> <span class="nav-text">case1 当前节点的父节点是红色，且当前节点的祖父节点的另一个子节点（叔叔节点）也是红色。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#case2-当前节点的父节点是红色，当前节点的叔叔节点为黑色。分为四种情况。在case2中只讨论前两种，后面两种归类为case3"><span class="nav-number">3.2.</span> <span class="nav-text">case2 当前节点的父节点是红色，当前节点的叔叔节点为黑色。分为四种情况。在case2中只讨论前两种，后面两种归类为case3</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#case3-当前节点的父节点是红色，当前节点的叔叔节点是黑色，和case2两种情况不同的是"><span class="nav-number">3.3.</span> <span class="nav-text">case3 当前节点的父节点是红色，当前节点的叔叔节点是黑色，和case2两种情况不同的是</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
